package likou.offer;

import java.util.List;

/**
 * @Info:
 * @Author: 唐小尊
 * @Date: 2020/8/4  19:13
 */
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}


public class _25 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);
        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);
        ListNode listNode = mergeTwoLists(l1,l2);

        while (listNode!=null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode list;
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        if (l1.val < l2.val) {
            list = l1;
            l1 = l1.next;
        } else {
            list = l2;
            l2 = l2.next;
        }
        ListNode daan = list;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                list.next = l1;
                l1 = l1.next;
                list = list.next;
            } else {
                list.next = l2;
                l2 = l2.next;
                list = list.next;
            }
        }
        if (l1 == null) {
            list.next = l2;
        } else {
            list.next = l1;
        }
        return daan;
    }
}
